import * as types from './mutation-type'
import {
	createStore
} from 'vuex'

export default createStore({
	state: {
		isLogin:false,
		shoppingCart:[],
		userName:''
	},
	mutations: {
		changeIslogin(state){
			state.isLogin=!state.isLogin
		},
		[types.PUSH_PRODUCT_TO_CART](state,product){
			state.shoppingCart.push({
				name:product.name,
				price:product.price,
				quantity:1,
				prices:this.price*this.quantity,
				description:product.description,
				isPay:false
			})
		},
		[types.INCREMENT_ITEM_QUANTITY](state,product){
			const cartItem=state.shoppingCart.find(item =>item.name===product.name)
			cartItem.quantity++
		},
		[types.DECREMENT_ITEM_QUANTITY](state,product){
			const cartItem=state.shoppingCart.find(item =>item.name===product.name)
			if(cartItem.quantity==0){
				state.shoppingCart.remove(cartItem)
			}
			else cartItem.quantity--
		},
		[types.REOMVE_ITEM_ALL](state){
			state.shoppingCart=[]
		},
		[types.PAY_SHOPPING_PRICE](state,product){
			const cartItem=state.shoppingCart.find(item =>item.name===product.name)
			cartItem.isPay=true
		},
	},
	actions: {
		addProductToCart:({commit,state},product)=>{
			const cartItem =state.shoppingCart.find(item =>item.name===product.name)
			if(!cartItem) commit(types.PUSH_PRODUCT_TO_CART,{name:product.name,price: product.price,description:product.description})
			else commit(types.INCREMENT_ITEM_QUANTITY,cartItem)
		},
		removeItemAll:({commit,state})=>{
		 	commit(types.REOMVE_ITEM_ALL)
		}
	},
	modules: {},
	getters:{
		login:state => {
			return state.isLogin
		},
		items:state=>{
			return state.shoppingCart
		},
		userName:state => {
			return state.userName
		}
	}
})
